<template>
  <view class="store-selector">
    <!-- <view class="header">
      <view class="title">选择门店</view>
      <view class="close" @tap="goBack">
        <text class="iconfont">×</text>
      </view>
    </view> -->
    
    <scroll-view 
      class="store-list" 
      scroll-y 
      @scrolltolower="loadMore"
      :style="{height: 'calc(100vh - 100rpx)'}"
    >
      <view 
        v-for="(store, index) in storeList" 
        :key="index" 
        class="store-item"
        :class="{ active: currentStore && currentStore.id === store.id }"
        @tap="selectStore(store)"
      >
        <view class="store-info">
          <view class="store-name">{{ store.name }}</view>
          <view class="store-address">{{ store.address }}</view>
          <view class="store-phone" v-if="store.phone">电话：{{ store.phone }}</view>
          <view class="store-time" v-if="store.businessHours">营业时间：{{ store.businessHours }}</view>
        </view>
        <view class="selected-icon" v-if="currentStore && currentStore.id === store.id">
          <text class="iconfont">✓</text>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="loading">
        <text>加载中...</text>
      </view>
      
      <!-- 加载完成提示 -->
      <view class="no-more" v-if="!loading && !hasMore && storeList.length > 0">
        <text>没有更多门店了</text>
      </view>
      
      <!-- 无数据提示 -->
      <view class="empty-tip" v-if="!loading && storeList.length === 0">
        暂无门店信息
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
import { fetchStoreList, fetchStoreListByPage } from '@/api/store'

export default {
  data() {
    return {
      loading: false,
      current: 1,
      size: 20,
      total: 0,
      hasMore: true
    }
  },
  computed: {
    ...mapState({
      currentStore: state => state.currentStore,
      storeList: state => state.storeList
    })
  },
  methods: {
    ...mapMutations([
      'setCurrentStore',
      'setStoreList'
    ]),
    ...mapActions([
      'initStoreInfo'
    ]),
    // 加载更多
    loadMore() {
      if (this.loading || !this.hasMore) return;
      this.current++;
      this.getStoreList(false);
    },
    // 获取门店列表
    async getStoreList(isReset = true) {
      try {
        this.loading = true;
        
        const params = {
          current: this.current,
          size: this.size,
          // 只显示状态为启用的门店(状态值根据后端定义)
          status: 1
        };
        
        const res = await fetchStoreListByPage(params);
        
        if (res.code === 200) {
          let records, total, pages;
          
          // 兼容不同的返回数据格式
          if (res.data.records) {
            // 标准分页格式
            records = res.data.records;
            total = res.data.total;
            pages = res.data.pages || Math.ceil(total / this.size);
          } else {
            // 如果是数组格式，直接使用
            records = Array.isArray(res.data) ? res.data : [];
            total = records.length;
            pages = 1;
          }
          
          // 更新总数和是否有更多数据
          this.total = total;
          this.hasMore = this.current < pages;
          
          if (isReset) {
            // 重置列表
            this.setStoreList(records);
          } else {
            // 追加到现有列表
            this.setStoreList([...this.storeList, ...records]);
          }
        }
        return Promise.resolve();
      } catch (error) {
        console.error('获取门店列表失败', error);
        uni.showToast({
          title: '获取门店列表失败',
          icon: 'none'
        });
        return Promise.reject(error);
      } finally {
        this.loading = false;
      }
    },
    selectStore(store) {
      // 确保门店ID是数字类型
      if (store && store.id && typeof store.id === 'string') {
        store.id = parseInt(store.id);
      }
      
      // 保存选择的门店到全局状态
      this.setCurrentStore(store);
      
      // 设置一个标记，表示门店刚刚被更新
      uni.setStorageSync('storeJustUpdated', 'true');
      
      uni.showToast({
        title: `已选择${store.name}`,
        icon: 'success',
        duration: 1000,
        success: () => {
          // 选择门店后立即跳转回菜单页面
          setTimeout(() => {
            const pages = getCurrentPages();
            // 如果上一页是点单页，直接回退
            if (pages.length > 1) {
              // 主动触发页面的刷新
              uni.navigateBack({
                delta: 1,
                success: () => {
                  // 确保返回后页面重新加载数据
                  console.log('返回上一页，门店已更新');
                  // 这里无法直接操作上一页的方法，所以通过storage标记来通知
                }
              });
            } else {
              // 跳转到点单页并刷新数据
              uni.switchTab({
                url: '/pages/menu/menu',
                success: () => {
                  console.log('跳转到点单页，门店已更新');
                  // switchTab成功后无法直接操作目标页面的方法，通过storage标记来通知
                }
              });
            }
          }, 1000);
        }
      });
    },
    goBack() {
      uni.navigateBack();
    }
  },
  onLoad() {
    // 先获取列表数据，再初始化门店信息
    this.getStoreList().then(() => {
      this.initStoreInfo();
    });
  }
}
</script>

<style lang="scss">
.store-selector {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .close {
      padding: 10rpx;
      .iconfont {
        font-size: 40rpx;
      }
    }
  }
  
  .store-list {
    padding: 20rpx;
    
    .store-item {
      position: relative;
      display: flex;
      justify-content: space-between;
      padding: 30rpx;
      margin-bottom: 20rpx;
      background-color: #fff;
      border-radius: 10rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      
      &.active {
        background-color: #f8f8f8;
        border: 1px solid #07c160;
      }
      
      .store-info {
        flex: 1;
        
        .store-name {
          font-size: 30rpx;
          font-weight: bold;
          margin-bottom: 10rpx;
        }
        
        .store-address, .store-phone, .store-time {
          font-size: 26rpx;
          color: #666;
          margin-top: 8rpx;
        }
      }
      
      .selected-icon {
        position: absolute;
        right: 20rpx;
        bottom: 20rpx;
        color: #07c160;
        font-size: 40rpx;
      }
    }
  }
  
  .loading-more, .no-more {
    padding: 20rpx 0;
    text-align: center;
    color: #999;
    font-size: 26rpx;
  }
  
  .empty-tip {
    padding: 100rpx 0;
    text-align: center;
    font-size: 28rpx;
    color: #999;
  }
}
</style> 